#!/bin/bash

# Setup some fixed vars
cd_mount_point="/mnt/cdrom"
tmp_install_dir="/tmp/install"
os_drive_dir="/mnt/os"

# If cd mount point doesn't exist, create it.
if [ ! -e "${cd_mount_point}" ]
then
    mkdir "${cd_mount_point}" &> /dev/null
fi

# If tmp install dir doesn't exist, create it.
if [ ! -e "${tmp_install_dir}" ]
then
    mkdir "${tmp_install_dir}" &> /dev/null
fi

# If the cdrom isn't mounted already, mount it
if [ ! "$(mount | grep "on ${cd_mount_point} type" &> /dev/null)" ]
then
    mount /dev/sr0 ${cd_mount_point}
fi

# Copy initrd to tmp install dir
cp "${cd_mount_point}/initrd.gz" "${tmp_install_dir}/" &> /dev/null
# Decompress initrd
gzip -d "${tmp_install_dir}/initrd.gz" &> /dev/null
# Make directory for initrd mount point
mkdir "${tmp_install_dir}/fs" &> /dev/null
# Mount initrd image to folder as a loopback and read-only.
mount -o loop,ro "${tmp_install_dir}/initrd" "${tmp_install_dir}/fs" &> /dev/null

# Partition the requested drive for installation.
fdisk "${desired_os_drive}" < "${fdisk_setup}" &> /dev/null
# Format the os partition to ext2.
mkfs.ext2 "${desired_os_drive}1" &> /dev/null
# Modify some settings for the fs
tune2fs -c 0 -i 0 "${desired_os_drive}1" &> /dev/null
# Make directory for os partition mount point
mkdir "${os_drive_dir}" &> /dev/null
# Mount the partition, copy the initrd structure to the os partition.
mount "${desired_os_drive}1" "${os_drive_dir}" &> /dev/null
# Setup boot loader on os drive
# TODO
# Make some modifications to the os partition for installed version.
# TODO
# Unmount os partition
umount "${os_drive_dir}" &> /dev/null
# Unmount initrd image
umount "${tmp_install_dir}/fs" &> /dev/null
# Unmount cdrom
umount "${cd_mount_point}" &> /dev/null
# Cleanup unneeded tmp files.
rm -Rf "${cd_mount_point}" &> /dev/null
